// Microi 核心配置和工具类
// 基于技术文档实现的登录鉴权系统

import { getMicroiConfig, getStorageKeys, isDebugEnabled } from './index'

// 获取统一配置
const microiConfig = getMicroiConfig()
const STORAGE_KEYS = getStorageKeys()

// 调试开关
const ConsoleLog = isDebugEnabled()

// 客户端配置 - 兼容旧版本
const configOsClient = {
  apibase: microiConfig.osClient.clients.apibase,
}

// 日期工具类
class DateUtils {
  // 添加时间
  static addTime(
    date: Date,
    unit: 'y' | 'M' | 'q' | 'w' | 'd' | 'h' | 'H' | 'm' | 'n' | 's',
    value: number
  ): Date {
    const newDate = new Date(date)
    switch (unit) {
      case 'y':
        newDate.setFullYear(newDate.getFullYear() + value)
        break
      case 'M':
        newDate.setMonth(newDate.getMonth() + value)
        break
      case 'q':
        newDate.setMonth(newDate.getMonth() + value * 3)
        break
      case 'w':
        newDate.setDate(newDate.getDate() + value * 7)
        break
      case 'd':
        newDate.setDate(newDate.getDate() + value)
        break
      case 'h':
      case 'H':
        newDate.setHours(newDate.getHours() + value)
        break
      case 'm':
      case 'n':
        newDate.setMinutes(newDate.getMinutes() + value)
        break
      case 's':
        newDate.setSeconds(newDate.getSeconds() + value)
        break
    }
    return newDate
  }

  // 格式化日期
  static format(date: Date, format: string): string {
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')

    return format
      .replace('yyyy', String(year))
      .replace('MM', month)
      .replace('dd', day)
      .replace('HH', hours)
      .replace('mm', minutes)
      .replace('ss', seconds)
  }
}

// 扩展Date原型
declare global {
  interface Date {
    AddTime(
      unit: 'y' | 'M' | 'q' | 'w' | 'd' | 'h' | 'H' | 'm' | 'n' | 's',
      value: number
    ): Date
    Format(format: string): string
    DiffTime(
      unit: 'y' | 'q' | 'M' | 'w' | 'd' | 'h' | 'H' | 'm' | 's',
      time2: Date
    ): number
  }
}

// 为Date原型添加方法
Date.prototype.AddTime = function (
  unit: 'y' | 'M' | 'q' | 'w' | 'd' | 'h' | 'H' | 'm' | 'n' | 's',
  value: number
): Date {
  return DateUtils.addTime(this, unit, value)
}

Date.prototype.Format = function (format: string): string {
  return DateUtils.format(this, format)
}

Date.prototype.DiffTime = function (
  unit: 'y' | 'q' | 'M' | 'w' | 'd' | 'h' | 'H' | 'm' | 's',
  time2: Date
): number {
  const d = this
  const t = d.getTime()
  const t2 = time2.getTime()

  const diff: Record<string, number> = {
    y: time2.getFullYear() - d.getFullYear(),
    q:
      Math.floor(time2.getMonth() / 4) -
      Math.floor(d.getMonth() / 4) +
      (time2.getFullYear() - d.getFullYear()) * 4,
    M:
      (time2.getFullYear() - d.getFullYear()) * 12 +
      time2.getMonth() -
      d.getMonth(),
    w:
      Math.floor((t2 + 345600000) / 604800000) -
      Math.floor((t + 345600000) / 604800000),
    d: Math.floor(t2 / 86400000) - Math.floor(t / 86400000),
    h: Math.floor(t2 / 3600000) - Math.floor(t / 3600000),
    H: Math.floor(t2 / 3600000) - Math.floor(t / 3600000),
    m: Math.floor(t2 / 60000) - Math.floor(t / 60000),
    s: Math.floor(t2 / 1000) - Math.floor(t / 1000),
  }

  return diff[unit] || 0
}

// 类型定义 - 导入统一类型
import type {
  UserInfo,
  SysConfig,
  MicroiApiResponse,
  RoleInfo,
  RoleLimitInfo,
  SysMenuHomePage,
} from '../types'

interface LoginParams {
  Account: string
  Pwd: string
  _CaptchaId?: string
  _CaptchaValue?: string
}

interface CaptchaResponse {
  Code: number
  CaptchaSrc: string
  CaptchaId: string
}

// Microi 核心类
class MicroiCore {
  // 客户端信息
  public OsClient: string = ''
  public ClientType: string = ''
  public ClientSystem: string = ''
  public ApiBase: string = ''

  // 系统配置
  public SysConfig: SysConfig = {}

  // 当前用户
  public CurrentUser: UserInfo | null = null

  constructor() {
    this.initClientInfo()
  }

  // 初始化客户端信息
  private initClientInfo(): void {
    // 获取客户端类型
    // #ifdef H5
    this.ClientType = 'H5'
    this.ClientSystem = 'H5'
    // #endif

    // #ifdef MP-WEIXIN
    this.ClientType = 'MP-WEIXIN'
    this.ClientSystem = 'WeChat'
    // #endif

    // #ifdef MP-ALIPAY
    this.ClientType = 'MP-ALIPAY'
    this.ClientSystem = 'Alipay'
    // #endif

    // #ifdef MP-BAIDU
    this.ClientType = 'MP-BAIDU'
    this.ClientSystem = 'Baidu'
    // #endif

    // #ifdef MP-TOUTIAO
    this.ClientType = 'MP-TOUTIAO'
    this.ClientSystem = 'Toutiao'
    // #endif

    // #ifdef APP-PLUS
    this.ClientType = 'APP'
    // #ifdef APP-ANDROID
    this.ClientSystem = 'Android'
    // #endif
    // #ifdef APP-HARMONY
    this.ClientSystem = 'HarmonyOS'
    // #endif
    // #ifdef APP-IOS
    this.ClientSystem = 'iOS'
    // #endif
    // #endif
  }

  // 获取客户端类型
  getClientType(): string {
    return this.ClientType
  }

  // 获取客户端系统
  getClientSystem(): string {
    return this.ClientSystem
  }

  // 获取API基础URL
  getApiBase(): string {
    return (
      this.ApiBase ||
      uni.getStorageSync(STORAGE_KEYS.API_BASE) ||
      configOsClient.apibase
    )
  }

  // 设置API基础URL
  setApiBase(url: string): void {
    this.ApiBase = url
    uni.setStorageSync(STORAGE_KEYS.API_BASE, url)
  }

  // 获取OsClient
  getOsClient(): string {
    return (
      this.OsClient ||
      uni.getStorageSync(STORAGE_KEYS.OS_CLIENT) ||
      microiConfig.osClient.default
    )
  }

  // 设置OsClient
  setOsClient(osClient: string): void {
    this.OsClient = osClient
    uni.setStorageSync(STORAGE_KEYS.OS_CLIENT, osClient)

    // 设置对应的API地址
    const clientUrl =
      microiConfig.osClient.clients[
        osClient as keyof typeof microiConfig.osClient.clients
      ]
    if (clientUrl) {
      this.setApiBase(clientUrl)
    } else {
      // 如果找不到对应的客户端配置，使用默认配置
      this.setApiBase(microiConfig.osClient.clients.apibase)
    }
  }

  // 获取Token
  getToken(): string | null {
    return uni.getStorageSync(STORAGE_KEYS.TOKEN) || null
  }

  // 设置Token
  setToken(token: string | null): void {
    if (token) {
      uni.setStorageSync(STORAGE_KEYS.TOKEN, token)
      // 设置过期时间（从配置中获取）
      const expires = new Date()
        .AddTime('m', microiConfig.token.expireMinutes)
        .Format('yyyy-MM-dd HH:mm:ss')
      uni.setStorageSync(STORAGE_KEYS.TOKEN_EXPIRES, expires)
    } else {
      uni.setStorageSync(STORAGE_KEYS.TOKEN, '')
      uni.setStorageSync(STORAGE_KEYS.TOKEN_EXPIRES, '')
    }
  }

  // 检查Token是否过期
  isTokenExpired(): boolean {
    const expires = uni.getStorageSync(STORAGE_KEYS.TOKEN_EXPIRES)
    if (!expires) return true

    const now = new Date()
    const expireTime = new Date(expires)
    return now >= expireTime
  }

  // 获取当前用户
  getCurrentUser(): UserInfo | null {
    return (
      this.CurrentUser || uni.getStorageSync(STORAGE_KEYS.USER_INFO) || null
    )
  }

  // 设置当前用户
  setCurrentUser(user: UserInfo | null): void {
    this.CurrentUser = user
    if (user) {
      uni.setStorageSync(STORAGE_KEYS.USER_INFO, user)
    } else {
      uni.removeStorageSync(STORAGE_KEYS.USER_INFO)
    }
  }

  // 检查是否已登录
  isLogin(): boolean {
    return !!(this.getToken() && this.getCurrentUser())
  }

  // 获取系统配置
  async getSysConfig(force = false): Promise<SysConfig> {
    if (!force && Object.keys(this.SysConfig).length > 0) {
      return this.SysConfig
    }

    try {
      const response = await this.Post('/api/DiyTable/getSysConfig', {
        OsClient: this.getOsClient(),
      })

      if (response.Code === 1) {
        this.SysConfig = response.Data || {}
        uni.setStorageSync(STORAGE_KEYS.SYS_CONFIG, this.SysConfig)
        return this.SysConfig
      }
    } catch (error) {
      console.error('获取系统配置失败:', error)
    }

    return this.SysConfig
  }

  // 获取验证码
  async getCaptcha(): Promise<CaptchaResponse> {
    const response = await this.Post('/api/Captcha/getCaptcha', {
      OsClient: this.getOsClient(),
    })
    return {
      Code: response.Code,
      CaptchaSrc: response.Data?.CaptchaSrc || '',
      CaptchaId: response.Data?.CaptchaId || '',
    }
  }

  // 用户登录
  async login(params: LoginParams): Promise<MicroiApiResponse> {
    console.log('Microi.login 接收到的参数:', params)

    // 构建完整的登录参数 - 确保参数顺序和格式完全匹配
    const loginParams = {
      Account: params.Account,
      Pwd: params.Pwd,
      _CaptchaId: params._CaptchaId || '',
      _CaptchaValue: params._CaptchaValue || '',
      _ClientType: this.ClientType,
      _ClientSystem: this.ClientSystem,
      OsClient: this.getOsClient(),
    }

    console.log('Microi.login 构建的参数:', loginParams)
    console.log(
      'Account 在构建后:',
      loginParams.Account,
      '长度:',
      loginParams.Account?.length
    )
    console.log(
      'Pwd 在构建后:',
      loginParams.Pwd,
      '长度:',
      loginParams.Pwd?.length
    )

    // 关键：使用form格式发送请求，匹配老项目
    const response = await this.Post(
      '/api/SysUser/login',
      loginParams,
      {},
      {
        DataType: 'form',
      }
    )

    if (response.Code === 1) {
      // 从响应头获取Token - 支持多种可能的字段名
      const token =
        response.headers?.Authorization ||
        response.headers?.authorization ||
        response.headers?.token ||
        response.Data?.token

      if (token) {
        this.setToken(token)
      }

      // 设置用户信息
      if (response.Data) {
        this.setCurrentUser({
          id: response.Data.Id || response.Data.id || '',
          username:
            response.Data.Account || response.Data.username || params.Account,
          token: token || '',
          refreshToken: response.Data.refreshToken || '',
          ...response.Data,
        })
      }
    }

    return response
  }

  // Token登录
  async tokenLogin(token: string): Promise<MicroiApiResponse> {
    const response = await this.Post(
      '/api/SysUser/TokenLogin',
      {
        _token: token,
        Token: token,
        TokenName: 'token',
        OsClient: this.getOsClient(),
      },
      {
        authorization: `Bearer ${token}`,
      }
    )

    if (response.Code === 1) {
      this.setToken(token)
      this.setCurrentUser(response.Data)
    }

    return response
  }

  // 刷新Token
  async refreshToken(callback?: (success: boolean) => void): Promise<boolean> {
    try {
      const token = this.getToken()
      if (!token || !this.isTokenExpired()) {
        if (callback) callback(true)
        return true
      }

      const response = await this.Post('/api/SysUser/refreshToken', {
        OsClient: this.getOsClient(),
      })

      if (response.Code === 1) {
        const newToken =
          response.headers?.Authorization ||
          response.headers?.authorization ||
          response.Data?.token
        if (newToken) {
          this.setToken(newToken)
        }
        if (callback) callback(true)
        return true
      } else {
        // Token刷新失败，清除登录状态
        this.logout()
        if (callback) callback(false)
        return false
      }
    } catch (error) {
      console.error('刷新Token失败:', error)
      this.logout()
      if (callback) callback(false)
      return false
    }
  }

  // 登出
  logout(): void {
    this.setToken(null)
    this.setCurrentUser(null)
    uni.clearStorageSync()
  }

  // 飞书登录
  async feishuLogin(code: string, appKey: string): Promise<MicroiApiResponse> {
    const response = await this.Post('/api/ApiEngine/run', {
      ApiKey: 'feishu_login',
      Data: {
        code: code,
        appKey: appKey,
      },
    })

    if (response.Code === 1) {
      this.setCurrentUser(response.Data.CurrentUser)
      this.setToken(response.Data.Token)
    }

    return response
  }

  // 获取服务器时间
  async getDateTimeNow(): Promise<string> {
    try {
      const response = await this.Post('/api/os/getDateTimeNow', {})
      return response.Data || new Date().toISOString()
    } catch (error) {
      return new Date().toISOString()
    }
  }

  // 添加系统日志
  async addSysLog(logData: {
    Type: string
    Title: string
    Api: string
    Param: string
    Content: string
  }): Promise<void> {
    try {
      await this.Post('/api/SysLog/addSysLog', {
        ...logData,
        OsClient: this.getOsClient(),
      })
    } catch (error) {
      console.error('添加系统日志失败:', error)
    }
  }

  // 通用POST请求
  async Post(
    url: string,
    data: any,
    headers: Record<string, string> = {},
    options: { DataType?: string } = {}
  ): Promise<MicroiApiResponse> {
    const apiBase = this.getApiBase()
    const fullUrl = `${apiBase}${url}`

    // 根据DataType设置content-type
    const dataType = options.DataType || 'json'
    const isFormData = dataType.toLowerCase() === 'form'

    const defaultHeaders: Record<string, string> = {
      accept: '*/*',
      'accept-language': 'zh-CN,zh;q=0.9',
      authorization: `Bearer ${this.getToken()}`,
      osclient: this.getOsClient(),
      clienttype: this.ClientType,
      clientsystem: this.ClientSystem,
      ...headers,
    }

    // 只有在非FormData时才设置content-type
    if (!isFormData) {
      defaultHeaders['content-type'] = 'application/json'
    }

    // 根据DataType处理数据格式
    let requestData = data
    if (dataType.toLowerCase() === 'form') {
      // 将对象转换为URL-encoded格式（服务器期望的格式）
      const formParams = new URLSearchParams()
      for (const key in data) {
        if (data[key] !== undefined && data[key] !== null) {
          formParams.append(key, String(data[key]))
        }
      }
      requestData = formParams.toString()
      defaultHeaders['content-type'] = 'application/x-www-form-urlencoded'
    }

    return new Promise((resolve, reject) => {
      uni.request({
        url: fullUrl,
        method: 'POST',
        data: requestData,
        header: defaultHeaders,
        success: (res: any) => {
          // 从响应头提取Token - 支持多种可能的字段名
          const token =
            res.header.Authorization ||
            res.header.authorization ||
            res.header.token ||
            res.header.Token

          if (token) {
            this.setToken(token)
          }

          resolve({
            Code: res.data?.Code || 0,
            Data: res.data?.Data,
            Msg: res.data?.Msg || '',
            headers: res.header,
          })
        },
        fail: (error: any) => {
          // 记录错误日志
          this.addSysLog({
            Type: '前端错误',
            Title: 'API请求失败',
            Api: fullUrl,
            Param: JSON.stringify(data),
            Content: error.errMsg || '网络请求失败',
          })

          reject({
            Code: 0,
            Data: error,
            Msg: error.errMsg || '网络请求失败',
          })
        },
      })
    })
  }

  // 通用GET请求
  async Get(
    url: string,
    params: Record<string, any> = {}
  ): Promise<MicroiApiResponse> {
    const apiBase = this.getApiBase()
    const fullUrl = `${apiBase}${url}`

    const queryString = Object.keys(params)
      .map(
        (key) => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`
      )
      .join('&')

    const finalUrl = queryString ? `${fullUrl}?${queryString}` : fullUrl

    return new Promise((resolve, reject) => {
      uni.request({
        url: finalUrl,
        method: 'GET',
        header: {
          'content-type': 'application/json',
          authorization: `Bearer ${this.getToken()}`,
          osclient: this.getOsClient(),
          clienttype: this.ClientType,
          clientsystem: this.ClientSystem,
        },
        success: (res: any) => {
          if (ConsoleLog) {
            console.log(`[Microi] GET ${url}:`, res)
          }

          // 从响应头提取Token
          const token = res.header.Authorization || res.header.authorization
          if (token) {
            this.setToken(token)
          }

          resolve({
            Code: res.data?.Code || 0,
            Data: res.data?.Data,
            Msg: res.data?.Msg || '',
            headers: res.header,
          })
        },
        fail: (error: any) => {
          if (ConsoleLog) {
            console.error(`[Microi] GET ${url} failed:`, error)
          }

          reject({
            Code: 0,
            Data: error,
            Msg: error.errMsg || '网络请求失败',
          })
        },
      })
    })
  }

  // 显示提示
  tips(message: string, success = true): void {
    uni.showToast({
      title: message,
      icon: success ? 'success' : 'none',
      duration: 2000,
    })
  }

  // 显示加载
  showLoading(title = '加载中...'): void {
    uni.showLoading({
      title,
      mask: true,
    })
  }

  // 隐藏加载
  hideLoading(): void {
    uni.hideLoading()
  }

  // 页面跳转
  routerPush(url: string): void {
    uni.navigateTo({ url })
  }

  // 初始化
  async init(param?: {
    TokenCallback?: (success: boolean) => void
  }): Promise<void> {
    try {
      // 1. 设置客户端类型
      this.ClientType = this.getClientType()
      this.ClientSystem = this.getClientSystem()

      // 2. 获取系统配置
      await this.getSysConfig(true)

      // 3. 自动登录（token以旧换新）
      await this.refreshToken(param?.TokenCallback)

      // 4. 获取当前登录用户身份信息
      await this.getCurrentUserInfo(true, param?.TokenCallback)

      // 5. 启动定时任务
      setInterval(() => {
        this.refreshToken(param?.TokenCallback)
      }, 1000 * microiConfig.token.refreshInterval) // Token刷新检查间隔

      setInterval(() => {
        this.getCurrentUserInfo(true, param?.TokenCallback)
      }, 1000 * microiConfig.token.userInfoInterval) // 用户信息更新间隔

      // 6. 获取服务器时间
      await this.initDateTimeNow()

      if (ConsoleLog) {
        console.log('[Microi] 初始化完成')
      }
    } catch (error) {
      console.error('[Microi] 初始化失败:', error)
    }
  }

  // 获取当前用户信息
  async getCurrentUserInfo(
    force = false,
    callback?: (success: boolean) => void
  ): Promise<void> {
    try {
      if (!force && this.CurrentUser) {
        if (callback) callback(true)
        return
      }

      const response = await this.Post('/api/SysUser/getCurrentUser', {
        OsClient: this.getOsClient(),
      })

      if (response.Code === 1) {
        this.setCurrentUser(response.Data)
        if (callback) callback(true)
      } else {
        if (callback) callback(false)
      }
    } catch (error) {
      console.error('获取用户信息失败:', error)
      if (callback) callback(false)
    }
  }

  // 初始化服务器时间
  async initDateTimeNow(): Promise<void> {
    try {
      await this.getDateTimeNow()
    } catch (error) {
      console.error('获取服务器时间失败:', error)
    }
  }

  // 表单引擎
  FormEngine = {
    // 新增数据
    AddFormData: async (
      formEngineKey: string,
      formData: Record<string, any>,
      callback?: (result: MicroiApiResponse) => void
    ): Promise<MicroiApiResponse> => {
      const param = {
        FormEngineKey: formEngineKey,
        Id: formData.Id || '',
        _RowModel: { ...formData },
      }
      delete param._RowModel.Id

      const result = await this.Post('/api/FormEngine/addFormData', param)
      if (callback) callback(result)
      return result
    },

    // 批量新增数据
    AddFormDataBatch: async (
      param: any,
      callback?: (result: MicroiApiResponse) => void
    ): Promise<MicroiApiResponse> => {
      const result = await this.Post('/api/FormEngine/addFormDataBatch', param)
      if (callback) callback(result)
      return result
    },

    // 删除数据
    DelFormData: async (
      param: any,
      callback?: (result: MicroiApiResponse) => void
    ): Promise<MicroiApiResponse> => {
      const result = await this.Post('/api/FormEngine/delFormData', param)
      if (callback) callback(result)
      return result
    },

    // 批量删除数据
    DelFormDataBatch: async (
      param: any,
      callback?: (result: MicroiApiResponse) => void
    ): Promise<MicroiApiResponse> => {
      const result = await this.Post('/api/FormEngine/delFormDataBatch', param)
      if (callback) callback(result)
      return result
    },

    // 修改数据
    UptFormData: async (
      formEngineKey: string,
      formData: Record<string, any>,
      callback?: (result: MicroiApiResponse) => void
    ): Promise<MicroiApiResponse> => {
      const param = {
        FormEngineKey: formEngineKey,
        Id: formData.Id || '',
        _RowModel: { ...formData },
      }
      delete param._RowModel.Id

      const result = await this.Post('/api/FormEngine/uptFormData', param)
      if (callback) callback(result)
      return result
    },

    // 获取单条数据
    GetFormData: async (
      formEngineKey: string,
      param: Record<string, any>,
      callback?: (result: MicroiApiResponse) => void
    ): Promise<MicroiApiResponse> => {
      const requestParam = {
        FormEngineKey: formEngineKey,
        ...param,
      }

      const result = await this.Post(
        `/api/FormEngine/getFormData-${formEngineKey}`,
        requestParam
      )
      if (callback) callback(result)
      return result
    },

    // 获取列表数据
    GetTableData: async (
      param: any,
      callback?: (result: MicroiApiResponse) => void
    ): Promise<MicroiApiResponse> => {
      const result = await this.Post('/api/FormEngine/getTableData', param)
      if (callback) callback(result)
      return result
    },
  }

  // 接口引擎
  ApiEngine = {
    Run: async (
      apiKey: string,
      data: Record<string, any>,
      callback?: (result: MicroiApiResponse) => void
    ): Promise<MicroiApiResponse> => {
      const param = {
        ApiEngineKey: apiKey,
        ...data,
      }

      const result = await this.Post('/api/ApiEngine/run', param, {
        IsApiEngine: 'true',
      })
      if (callback) callback(result)
      return result
    },
  }

  // 模块引擎
  ModuleEngine = {
    Run: async (
      moduleKey: string,
      data: Record<string, any>,
      callback?: (result: MicroiApiResponse) => void
    ): Promise<MicroiApiResponse> => {
      const param = {
        ModuleEngineKey: moduleKey,
        ...data,
      }

      const result = await this.Post('/api/ModuleEngine/run', param)
      if (callback) callback(result)
      return result
    },
  }

  // 文件上传
  async uploadFile(
    param: {
      File: string
      Path?: string
      Limit?: boolean
      Preview?: boolean
      _UseUniappUpload?: boolean
      _Anonymous?: boolean
    },
    callback?: (result: MicroiApiResponse) => void
  ): Promise<MicroiApiResponse> {
    if (!param.File) {
      this.tips('前端参数错误！', false)
      return { Code: 0, Data: null, Msg: '前端参数错误！' }
    }

    const uploadParam = {
      ...param,
      _ClientType: this.ClientType,
      _ClientSystem: this.ClientSystem,
      OsClient: this.getOsClient(),
    }

    const header = {
      authorization: `Bearer ${this.getToken()}`,
      osclient: this.getOsClient(),
      clienttype: this.ClientType,
      clientsystem: this.ClientSystem,
    }

    let uploadUrl = `${this.getApiBase()}/api/HDFS/upload`
    if (uploadParam._UseUniappUpload) {
      uploadUrl = uploadParam._Anonymous
        ? `${this.getApiBase()}/api/HDFS/uniappUploadAnonymous`
        : `${this.getApiBase()}/api/HDFS/uniappUpload`
    } else if (uploadParam._Anonymous) {
      uploadUrl = `${this.getApiBase()}/api/HDFS/uploadAnonymous`
    }

    this.showLoading('上传中...')

    return new Promise((resolve, reject) => {
      uni.uploadFile({
        url: uploadUrl,
        filePath: uploadParam.File,
        name: 'file',
        header,
        formData: uploadParam,
        success: (res: any) => {
          this.hideLoading()
          let result: MicroiApiResponse
          try {
            result = JSON.parse(res.data)
          } catch (e) {
            result = { Code: 0, Data: res, Msg: '解析响应失败' }
          }
          if (callback) callback(result)
          resolve(result)
        },
        fail: (res: any) => {
          this.hideLoading()
          const result = { Code: 0, Data: res, Msg: res.errMsg }
          if (callback) callback(result)
          reject(result)
        },
      })
    })
  }

  // 工具方法
  hidePhone(phone: string): string {
    if (!phone) return phone
    if (phone.length === 11) {
      return phone.substring(0, 3) + '****' + phone.substring(7)
    }
    const len = Math.floor(phone.length / 3)
    const none = '*'.repeat(phone.substring(len, phone.length - len).length)
    return phone.substring(0, len) + none + phone.substring(phone.length - len)
  }

  isImage(link: string): boolean {
    const imgExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp']
    const realLink = link.split('?')[0]
    const fileExtension = realLink
      .substring(realLink.lastIndexOf('.'))
      .toLowerCase()
    return imgExtensions.includes(fileExtension)
  }

  getCountStr(count: number): string {
    if (!count) return '0'
    if (count < 10000) return count.toString()
    if (count < 100000) return (count / 10000).toFixed(2) + '万'
    return (count / 10000).toFixed(1) + '万'
  }

  // 跳转到小程序
  navigateToMiniProgram(
    appId: string,
    path: string,
    param: any,
    callback?: (result: MicroiApiResponse) => void
  ): void {
    uni.navigateToMiniProgram({
      appId,
      path,
      extraData: param,
      success: (res: any) => {
        if (callback) callback({ Code: 1, Data: res, Msg: '' })
      },
      fail: (err: any) => {
        if (callback) callback({ Code: 0, Data: err, Msg: err.errMsg })
      },
    })
  }
}

// 创建全局实例
const Microi = new MicroiCore()

// 导入V8引擎
import { V8 } from './v8.engine'

// 将V8引擎挂载到Microi实例
;(Microi as any).V8 = V8

// 导出
export default Microi
export { MicroiCore, STORAGE_KEYS, configOsClient, V8 }
export type {
  UserInfo,
  SysConfig,
  LoginParams,
  CaptchaResponse,
  MicroiApiResponse,
}
